package vip.xiaonuo.issued.impl.device;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.facedoor.iservice.IDeviceSetService;
import vip.xiaonuo.facedoor.iservice.issulog.DeviceLogService;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceChangeTypeEnum;
import vip.xiaonuo.facedoor.modular.device.listener.DevicePublisher;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceSourceEnum;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.mapper.DeviceBaseMapper;
import vip.xiaonuo.facedoor.modular.deviceset.entity.DwDeviceSet;
import vip.xiaonuo.facedoor.modular.deviceset.param.DwDeviceSetParam;
import vip.xiaonuo.facedoor.modular.deviceset.service.DwDeviceSetService;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Map;

import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.issued.inter.MqttGateway;
import vip.xiaonuo.issued.bean.CMD;
import vip.xiaonuo.issued.bean.Topic;
import vip.xiaonuo.issued.util.SnowIdGen;

@Service(value = RuleConstant.DW + RuleConstant.DEVICE_SET)
@Slf4j
public class MqttDeviceSetServiceImpl implements IDeviceSetService {


  @Resource
  private DeviceBaseMapper deviceBaseMapper;

  @Resource
  private DwDeviceSetService dwDeviceSetService;

  @Resource
  private MqttGateway mqttGateWay;

  @Resource
  private DeviceLogService logService;

  @Resource
  private DevicePublisher publisher;

  @Override
  public void saveOrUpdate(DwDeviceSetParam dwDeviceSetParam) {
    try {
      log.info("--------------配置下发--------------");
      DeviceBase deviceBase = deviceBaseMapper.selectById(dwDeviceSetParam.getDeviceBaseId());
      Map<String, Object> map = SnowIdGen.getBaseMap();
      map.put("uploadFeaturePath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadFeature");
      map.put("uploadRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/reportData");
      map.put("uploadChildRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadChildRecord");
      map.put("uploadPersonVerificationRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadIdCardRecord");
      map.put("reportHealthData", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/reportHealthData");
      map.put("getTimePath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/getCurrentTime");
      map.put("deviceName", deviceBase.getName());
      map.put("deviceId", deviceBase.getId());
      map.put("cmd", CMD.UPLOAD_PARAM);
      map.put("key","ABCD1234");
      if(StringUtil.equals(deviceBase.getDeviceType(),"5")){// 存储柜设备下发特有属性
        map.put("maxUsageNum", dwDeviceSetParam.getMaxUseNum());
        map.put("adminPwd", dwDeviceSetParam.getAdminPwd());
        deviceBase.setMaxUseNum(dwDeviceSetParam.getMaxUseNum());
        deviceBase.setAdminPwd(dwDeviceSetParam.getAdminPwd());
      }
      String req = JSON.toJSONString(map);
      mqttGateWay.sendToMqtt(MessageFormat.format(Topic.DEVICE_TOPIC, deviceBase.getId()), 1, req);
      logService.addDeviceLog("",deviceBase.getName(), req, CMD.UPLOAD_PARAM, map.get(CMD.SERIAL_NUMBER).toString());
      DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, dwDeviceSetParam.getDeviceBaseId()));
      if (deviceSet == null) {
        dwDeviceSetService.add(dwDeviceSetParam);
      } else {
        dwDeviceSetService.edit(dwDeviceSetParam);
      }
      deviceBase.setCabinetIp(dwDeviceSetParam.getIp());
      deviceBase.setCabinetPort(dwDeviceSetParam.getCabinetPort());
      deviceBaseMapper.updateById(deviceBase);
      publisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.BASE,deviceBase);
    } catch (Exception e) {
      throw new ServiceException(500, "发生异常！异常信息为：" + ExceptionUtils.getMessage(e));
    }
  }

  @Override
  public void restart(String deviceId) {
    DeviceBase deviceBase = deviceBaseMapper.selectById(deviceId);
    if (deviceBase == null) {
      throw new ServiceException(500, "找不到设备！");
    }
    if (deviceBase.getDeviceState() != null && !deviceBase.getDeviceState().equals("1")) {
      throw new ServiceException(500, "远程重启失败！设备未在线");
    }
    try {
      Map<String, Object> baseMap = SnowIdGen.getBaseMap();
      baseMap.put(CMD.CMD, CMD.REBOOT_DEVICE);
      baseMap.put("deviceId", Long.parseLong(deviceId));
      String req = JSON.toJSONString(baseMap);
      mqttGateWay.sendToMqtt(MessageFormat.format(Topic.DEVICE_TOPIC, deviceId), 1, req);
      logService.addDeviceLog("",deviceBase.getName(), req, CMD.REBOOT_DEVICE, baseMap.get(CMD.SERIAL_NUMBER).toString());
    } catch (Exception e) {
      throw new ServiceException(500, "设备远程重启失败，原因：" + ExceptionUtils.getMessage(e));
    }
  }


}
